package com.zzx.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;



import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;



public class TestMain {
	private static File file = new File("src/main/resources/xml/my.xml");
	public static void main(String[] args) {
		//saveXml();
		//addXml();
		delXml();
	}
	/**
	 * 删除 xml 里面的内容
	 */
	public static void delXml() {
		 SAXReader reader = new SAXReader();
		 try {
			Document document = reader.read(file);
			// 通过document对象获取根节点bookstore
            Element root = document.getRootElement();
            Iterator it = root.elementIterator();
            List list1 = root.elements(); 
            boolean bf = true;
           // while (it.hasNext()) {
            for(int j=0;j<list1.size();j++){
            	//Map<String,String> map = (Map<String, String>) it.next();
            	Element map = (Element) it.next();
            	//Iterator itt = map.elementIterator();
            	List list = map.elements();
            	for(int i=0;i<list.size();i++){
            		Element bookChild = (Element) list.get(i);//.next();
            		System.err.println(j+ "节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
            		String id = bookChild.getStringValue();
                	if(null != id && "4".equals(id)) {
                		System.err.println("*准备删除**" + i);                		
                		Node person = root.selectSingleNode("/list/map["+(j+1)+"]");
                		
                		System.err.println("**"+person);
                		//移出节点
                		root.remove(person);
                		bf = false;
                		break;
                    }
            	}
            	if(!bf) {
            		break;
            	}
//            	while(itt.hasNext()) {
//            		Element bookChild = (Element) itt.next();
//                	//System.err.println("节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
//                   // System.err.println("***当前节点号："+bookChild.getNodeTypeName());
//                	String id = bookChild.getStringValue();
//                	if(null != id && "4".equals(id)) {
//                		System.err.println("*准备删除**");                		
//                		//Node person = root.selectSingleNode("/persons/person[2]");
//                		Node person = root.selectSingleNode("attribute::lang");
//                		Attribute nameAttribute = root.attribute("lang");// 得到当前节点的属性对象
//                	
//                		//rattribute::lang
//                		//root.select
//                		System.err.println("**"+person);
//                		//移出节点
//                		root.remove(person);
//
//                    }
//            	}
            	System.err.println("****"+map.toString());
            }
    		
    		// 按照指定格式将dom打印到xml文件中
            OutputFormat of = OutputFormat.createCompactFormat();
    		XMLWriter writer = new XMLWriter(new FileWriter("src/main/resources/xml/my.xml"), of);//构造一个具有良好输出格式的XML输出对象
            writer.write(document);
            writer.close();
    		System.err.println("******结束");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 往已经存在的 xml后面追加数据 数据格式 List<Map<String,String>>
	 */
	public static void addXml() {
		
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = new HashMap<String,String>();
        map.put("id", "6");
        map.put("name", "小明");
        map.put("age", "35");
        map.put("sex", "女");
        map.put("money", "6666");
        
        Map<String,String> map1 = new HashMap<String,String>();
        map1.put("id", "7");
        map1.put("name", "小红");
        map1.put("age", "18");
        map1.put("sex", "女");
        map1.put("money", "7777");
        
        list.add(map);
        list.add(map1);
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。\\src\\main\\resources\\xml/books.xml
        	//new BufferedInputStream(new FileInputStream("src/main/resources/text.properties"));
            Document document = reader.read(file);
            // 通过document对象获取根节点bookstore
            Element root = document.getRootElement();
            //创建一个新的person节点
    		for(Map<String,String> mm : list) {
    			//Element person = document.createElement("list");
        		Element newEle = root.addElement("map");
        		newEle.addElement("id").setText(mm.get("id"));
        		newEle.addElement("name").setText(mm.get("name"));
        		newEle.addElement("age").setText(mm.get("age"));
        		newEle.addElement("sex").setText(mm.get("sex"));
        		newEle.addElement("money").setText(mm.get("money"));
//        		//创建person的几个子节点
//                Element id = newEle.addElement("id");
//        		Element name = newEle.addElement("name");
//        		Element age = newEle.addElement("age");
//        		Element sex = newEle.addElement("sex");
//        		Element money = newEle.addElement("money");
//        		//给子节点设置值
//        		name.addText(mm.get("id"));
//        		age.addText(mm.get("name"));
//        		sex.addText(mm.get("age"));
//        		id.addText(mm.get("sex"));
//        		money.addText(mm.get("money"));        		     		
        		//将person追加到根节点
        		//root.appendContent(newEle);
    		}
    		OutputFormat of = OutputFormat.createCompactFormat();
    		XMLWriter writer = new XMLWriter(new FileWriter("src/main/resources/xml/my.xml"), of);//构造一个具有良好输出格式的XML输出对象
            writer.write(document);
            writer.close();
    		System.err.println("******结束");
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
	}
	/**
	 * 创建新的 xml 并写入数据。入参格式：List<Map<String,String>>
	 */
	public static void saveXml() {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String,String> map = new HashMap<String,String>();
        map.put("id", "1");
        map.put("name", "张三");
        map.put("age", "25");
        map.put("sex", "男");
        map.put("money", "5000");
        
        Map<String,String> map1 = new HashMap<String,String>();
        map1.put("id", "2");
        map1.put("name", "李四");
        map1.put("age", "28");
        map1.put("sex", "男");
        map1.put("money", "7000");
        
        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("id", "3");
        map2.put("name", "王五");
        map2.put("age", "29");
        map2.put("sex", "女");
        map2.put("money", "8765");
        
        Map<String,String> map3 = new HashMap<String,String>();
        map3.put("id", "4");
        map3.put("name", "赵六");
        map3.put("age", "32");
        map3.put("sex", "男");
        map3.put("money", "5550");
        
        Map<String,String> map4 = new HashMap<String,String>();
        map4.put("id", "5");
        map4.put("name", "张晓明");
        map4.put("age", "22");
        map4.put("sex", "女");
        map4.put("money", "9872");
        
		list.add(map);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
		//创建dom对象：
		Document dom = DocumentHelper.createDocument();

//	    2：创建根节点：
		Element root = dom.addElement("list");
//
		for(Map<String,String> mm : list){
			Element empEle = root.addElement("map");
			
			Element idEle = empEle.addElement("id");
			idEle.addText(mm.get("id")+""); 
			//添加name信息
            Element nameEle = empEle.addElement("name");
            nameEle.addText(mm.get("name"));
            Element ageEle = empEle.addElement("age");
            ageEle.addText(mm.get("age"));
            Element sexEle = empEle.addElement("sex");
            sexEle.addText(mm.get("sex"));
            Element moneyEle = empEle.addElement("money");
            moneyEle.addText(mm.get("money"));
           // moneyEle.setAttributeValue("money", mm.get("money"));
            //File xmlFlie = new File("src/main/resources/xml/my.xml");
            //4
            try {
            	XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
              //  FileOutputStream fos = new FileOutputStream("src/main/resources/xml/my.xml");
                FileOutputStream fos=new FileOutputStream(new File("src/main/resources/xml/my.xml"));
                writer.setOutputStream(fos);
                
                //5
                writer.write(dom);
                System.out.println("写出完毕!");
                writer.close();
            } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}     
            
		}
	}
	/**
	 * 读取 xml文件内容
	 * @return
	 */
	public static List<Map<String,String>> getDom4jXml() {
		List<Map<String,String>> bookList = new ArrayList<Map<String,String>>();
		// 解析books.xml文件
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。\\src\\main\\resources\\xml/books.xml
        	//new BufferedInputStream(new FileInputStream("src/main/resources/text.properties"));
            Document document = reader.read(new File("src/main/resources/xml/books.xml"));
            // 通过document对象获取根节点bookstore
            Element bookStore = document.getRootElement();
            // 通过element对象的elementIterator方法获取迭代器
            Iterator it = bookStore.elementIterator();
            // 遍历迭代器，获取根节点中的信息（书籍）
            while (it.hasNext()) {
                Map<String,String> map = new HashMap<String,String>();
            	System.out.println("=====开始遍历某一本书=====");
                Element book = (Element) it.next();
                // 获取book的属性名以及 属性值
                List<Attribute> bookAttrs = book.attributes();
                for (Attribute attr : bookAttrs) {//读取一级节点 属性名和值                   
                    map.put(attr.getName(), attr.getValue());
                	System.out.println("属性名：" + attr.getName() + "--属性值："
                            + attr.getValue());
                }
                Iterator itt = book.elementIterator();
                while (itt.hasNext()) {//读取下级节点里面的值。                    
                	Element bookChild = (Element) itt.next();
                	System.out.println("节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
                    map.put(bookChild.getName(), bookChild.getStringValue());
                    
                }
                bookList.add(map);
                System.out.println("=====结束遍历某一本书=====");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bookList;       
	}	
}
